package com.jrx.anytxn.reporting.job.xib.config;

import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.entity.AmlIATrading;
import com.jrx.anytxn.reporting.job.unionFile.step.UnionRepayFileReader;
import com.jrx.anytxn.reporting.job.xib.bean.AmlIATradingBean;
import com.jrx.anytxn.reporting.job.xib.step.*;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import com.jrx.anytxn.transaction.entity.TlInterestAccrualLog;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;

/**
 * 反洗钱（放款,还款,增加利息计提，罚息计提）
 */
@Configuration
@EnableConfigurationProperties(AnyTxnBatchProperties.class)
@EnableBatchProcessing
public class GenerateTradingConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GenerateTradingConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnyTxnBatchProperties anyTxnBatchProperties;
    @Autowired
    private TradingListener tradingListener;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private TradingProcessor tradingProcessor;
    @Autowired
    private TradingWriter tradingWriter;
    @Autowired
    private TradingPaymentProcessor tradingPaymentProcessor;
    @Autowired
    private TradingPaymentWriter tradingPaymentWriter;
    @Autowired
    private AccruedSerialProcessor accruedSerialProcessor;
    @Autowired
    private AccruedSerialWriter accruedSerialWriter;

    @Bean
    public Job generateTradingJob() {
        return jobBuilderFactory.get("generateTradingJob").incrementer(new RunIdIncrementer()).listener(tradingListener)
                .start(generateLoanStep())
                .next(generatePaymentStep())
//                .next(accruedSerialStep())//利息计提，罚息计提(暂时不上传)
                .build();
    }

    @Bean
    public Step generateLoanStep(){
        return stepBuilderFactory.get("generateLoanStep")
                .<AmLoanMainInfo, AmlIATrading>chunk(anyTxnBatchProperties.getReportingCustomerConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(loanReader())
                .processor(tradingProcessor)
                .writer(tradingWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getReportingCustomerConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    public Step generatePaymentStep(){
        return stepBuilderFactory.get("generateLoanStep")
                .<TlPaymentLog, AmlIATradingBean>chunk(anyTxnBatchProperties.getReportingCustomerConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(paymentReader())
                .processor(tradingPaymentProcessor)
                .writer(tradingPaymentWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getReportingCustomerConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    public Step accruedSerialStep(){
        return stepBuilderFactory.get("accruedSerialStep")
                .<TlInterestAccrualLog, AmlIATrading>chunk(anyTxnBatchProperties.getReportingCustomerConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(accruedSerialReader())
                .processor(accruedSerialProcessor)
                .writer(accruedSerialWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getReportingCustomerConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public MyBatisPagingItemReader<AmLoanMainInfo> loanReader(){
        logger.info("抽取订单批量启动,机构号：{}", ReportingConstant.DEFAULT_ORG_NUMBER);
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        return new LoanReader(sqlSessionFactory,anyTxnBatchProperties.getReportingLoanAcctConfig().getPageSize(),org);
    }

    @Bean
    @StepScope
    public ItemReader<TlPaymentLog> paymentReader(){
        logger.info("抽取还款流水启动,机构：{}", ReportingConstant.DEFAULT_ORG_NUMBER);
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        return new UnionRepayFileReader(sqlSessionFactory,anyTxnBatchProperties.getFileConfig().getPageSize(),org);
    }

    @Bean
    @StepScope
    public MyBatisPagingItemReader<TlInterestAccrualLog> accruedSerialReader() {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        return new AccruedSerialReader(sqlSessionFactory, org,anyTxnBatchProperties.getFileConfig().getPageSize());
    }
}
